<template>
  <div class="app-container">
    <el-row type="flex" :gutter="20" align="middle">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
        <el-col :span="6">
          <el-form-item label="图书名" prop="libBookName">
            <el-input
              v-model="queryParams.libBookName"
              placeholder="请输入图书名"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="图书分类" prop="libBookType">
            <el-select v-model="queryParams.libBookType"
                       placeholder="请选择图书分类"
                       clearable
                       filterable
            >
              <el-option
                v-for="dict in dict.type.lib_book_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="图书作者" prop="libBookAuthor">
            <el-input
              v-model="queryParams.libBookAuthor"
              placeholder="请输入图书作者"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="出版社" prop="libBookPublishHouse">
            <el-select v-model="queryParams.libBookPublishHouse"
                       placeholder="请选择出版社"
                       clearable
                       filterable
            >
              <el-option v-for="dict in dict.type.lib_book_publish_house"
                         :key="dict.value"
                         :label="dict.label"
                         :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label="出版时间"
                        prop="libBookPublishTime"
          >
            <el-date-picker v-model="queryParams.rangeMonth"
                            style="width: 400px"
                            type="monthrange"
                            value-format="yyyy-MM"
                            align="center"
                            unlink-panels
                            range-separator="至"
                            start-placeholder="开始月份"
                            end-placeholder="结束月份"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :offset="2" :span="6">
          <!--  TODO 修改为数量范围    -->
          <el-form-item label="图书库存" prop="libBookStockRule">
            <!--      lib_book_stock      -->
            <el-select v-model="queryParams.libBookStockRule"
                       placeholder="请选择图书库存"
                       clearable
                       filterable
            >
              <el-option v-for="i in bookStockRule"
                :label="i.label"
                :value="i.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <!--  TODO 修改为数量范围    -->
          <el-form-item label="图书价格" prop="libBookPrice">
            <el-input
              v-model="queryParams.libBookPrice"
              placeholder="请输入图书价格"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :offset="20">
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-col>
      </el-form>
    </el-row>

    <el-row :gutter="15" class="mb8" align="right">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['library:book:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['library:book:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['library:book:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['library:book:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :columns="rightToolBar.columns"
                     :showSearch.sync="showSearch"
                     @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="bookList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="序号" fixed align="center" type="index" width="150"
                       v-if="rightToolBar.columns[0].visible"
      />
      <el-table-column label="书名" align="center" width="150"
                       v-if="rightToolBar.columns[1].visible"
      >
        <template slot-scope="scope">
          <el-link @click="showBookIntroductionCard(scope.row)">{{ scope.row.libBookName }}</el-link>
        </template>
      </el-table-column>
      <el-table-column label="图书封面" align="center" prop="libBookCover" width="150"
                       v-if="rightToolBar.columns[2].visible"
      >
        <template slot-scope="scope">
          <image-preview :src="scope.row.libBookCover" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="图书分类" align="center" prop="libBookType" width="150"
                       v-if="rightToolBar.columns[3].visible"
      >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.lib_book_type" :value="scope.row.libBookType"/>
        </template>
      </el-table-column>
      <el-table-column label="图书作者" align="center" prop="libBookAuthor" width="150"
                       v-if="rightToolBar.columns[4].visible"
      />
      <el-table-column label="图书出版社" align="center" prop="libBookPublishHouse" width="150"
                       v-if="rightToolBar.columns[5].visible"
      >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.lib_book_publish_house" :value="scope.row.libBookPublishHouse"/>
        </template>
      </el-table-column>
      <el-table-column label="图书出版时间" align="center" prop="libBookPublishTime" width="180"
                       v-if="rightToolBar.columns[6].visible"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.libBookPublishTime, '{y}-{m}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="图书状态" align="center" prop="libBookStatus" width="150"
                       v-if="rightToolBar.columns[7].visible"
      >
        <template slot-scope="scope">
          <el-tooltip :content="scope.row.libBookStatus==='0'?'开放':'关闭'" placement="top">
            <el-switch
              style="display: block"
              v-model="scope.row.libBookStatus==='0'"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="changeBookStatus(scope.row)"
            >
            </el-switch>
          </el-tooltip>
          <!--          <dict-tag :options="dict.type.lib_book_status" :value="scope.row.libBookStatus"/>-->
        </template>
      </el-table-column>
      <el-table-column label="图书库存（本）" align="center" prop="libBookStock" width="150"
                       v-if="rightToolBar.columns[8].visible"
      />
      <el-table-column label="图书价格（元）" align="center" prop="libBookPrice" width="150"
                       v-if="rightToolBar.columns[9].visible"
      />
      <el-table-column label="操作" align="center" fixed="right" class-name="small-padding fixed-width" width="150">
        <template slot-scope="scope">
          <el-button type="success" plain size="small"
                     @click="handleUpdate(scope.row)"
                     v-hasPermi="['library:book:edit']"
          >
            修改
          </el-button>
          <el-divider direction="vertical"/>
          <el-button type="danger" plain size="small"
                     @click="handleDelete(scope.row)"
                     v-hasPermi="['library:book:remove']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!--  图书介绍对话框>卡片  -->
    <el-dialog :visible.sync="bookIntroductionDialog.open"
               width="600px"
               append-to-body
               :close-on-click-modal="false"
               :close-on-press-escape="false"
               :lock-scroll="false"
               custom-class="scroll-dialog"
               style="margin-top: 100px"
    >
      <image-preview :src="bookIntroductionDialog.cover" :width="50" :height="50"/>
      <br>
      <b>图书介绍：</b>
      <hr>
      <i>{{ bookIntroductionDialog.introduction }}</i>
    </el-dialog>

    <!-- 添加或修改图书馆-图书对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body
               :close-on-click-modal="false"
               :close-on-press-escape="false"
               :lock-scroll="false"
               custom-class="scroll-dialog"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="130px">
        <el-form-item label="图书名" prop="libBookName">
          <el-input v-model="form.libBookName" placeholder="请输入图书名"/>
        </el-form-item>
        <el-form-item label="图书封面" prop="libBookCover">
          <image-upload :limit="1" v-model="form.libBookCover"/>
        </el-form-item>
        <el-form-item label="图书介绍" prop="libBookIntroduction">
          <el-input v-model="form.libBookIntroduction" type="textarea" placeholder="请输入内容"
                    :autosize="{ minRows: 4, maxRows: 8}"/>
        </el-form-item>
        <el-form-item label="图书分类" prop="libBookType">
          <el-select v-model="form.libBookType" placeholder="请选择图书分类">
            <el-option
              v-for="dict in dict.type.lib_book_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="图书作者" prop="libBookAuthor">
          <el-input v-model="form.libBookAuthor" placeholder="请输入图书作者"/>
        </el-form-item>
        <el-form-item label="出版社" prop="libBookPublishHouse">
          <el-select v-model="form.libBookPublishHouse" placeholder="请选择图书出版社">
            <el-option
              v-for="dict in dict.type.lib_book_publish_house"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="出版时间" prop="libBookPublishTime">
          <el-date-picker clearable
                          v-model="form.libBookPublishTime"
                          type="month"
                          value-format="yyyy-MM"
                          placeholder="请选择图书出版时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="图书库存（本）" prop="libBookStock">
          <el-input v-model="form.libBookStock" placeholder="请输入图书库存"/>
        </el-form-item>
        <el-form-item label="图书价格（元）" prop="libBookPrice">
          <el-input v-model="form.libBookPrice" placeholder="请输入图书价格"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {getBook, delBook, addBook, updateBook, pageBook, changeBookStatus} from "@/api/library/book";
import {BOOK_CLOSED_STATUS, BOOK_OPEN_STATUS} from '../const'
import {SUCCESS_MSG, ERROR_MSG} from "@/const/crud_notification_const";

export default {
  name: "Book",
  dicts: ['lib_book_type', 'lib_book_publish_house', 'lib_book_status', 'lib_book_stock'],
  data() {
    return {
      // 自定义库存规则
      bookStockRule:[
        {id:1,label:"无库存",value:0},
        {id:2,label:"库存不足",value:4},
        {id:3,label:"库存充足",value:5},
      ],
      // right-toolbar
      rightToolBar: {
        columns: [
          {id: 0, label: "序号", visible: true},
          {id: 1, label: "书名", visible: true},
          {id: 2, label: "图书封面", visible: true},
          {id: 3, label: "图书分类", visible: true},
          {id: 4, label: "图书作者", visible: true},
          {id: 5, label: "出版社", visible: true},
          {id: 6, label: "出版时间", visible: true},
          {id: 7, label: "图书状态", visible: true},
          {id: 8, label: "图书库存", visible: true},
          {id: 9, label: "图书价格", visible: true},
        ],
      },

      // 图书介绍弹出框
      bookIntroductionDialog: {
        cover: null,
        title: null,
        introduction: null,
        open: false,
      },
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 图书馆-图书表格数据
      bookList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        libBookStockRule: null,//库存规则
        rangeMonth: null,//时间范围
        pageNum: 1,
        pageSize: 10,
        libBookId: null,
        libBookName: null,
        libBookCover: null,
        libBookIntroduction: null,
        libBookType: null,
        libBookAuthor: null,
        libBookPublishHouse: null,
        libBookStatus: null,
        libBookPrice: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        libBookName: [
          {required: true, message: '请输入图书名', trigger: 'blur'},
        ],
        libBookCover: [
          {required: true, message: '请上传图书封面', trigger: 'blur'}
        ],
        libBookIntroduction: [
          {required: true, message: '请输入图书介绍', trigger: 'blur'}
        ],
        libBookType: [
          {required: true, message: '请选择图书分类', trigger: 'blur'}
        ],
        libBookAuthor: [
          {required: true, message: '请输入图书作者', trigger: 'blur'}
        ],
        libBookPublishHouse: [
          {required: true, message: '请选择出版社', trigger: 'blur'}
        ],
        libBookPublishTime: [
          {required: true, message: '请选择出版时间', trigger: 'blur'}
        ],
        libBookStock: [
          {required: true, message: '请输入图书库存', trigger: 'blur'}
        ],
        libBookPrice: [
          {required: true, message: '请输入图书价格', trigger: 'blur'}
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    // 改变当前图书的状态
    changeBookStatus(row) {
      const libBookStatus = row.libBookStatus === BOOK_OPEN_STATUS ? BOOK_CLOSED_STATUS : BOOK_OPEN_STATUS;
      const libBookId = row.libBookId;
      const param = {libBookId, libBookStatus};
      const info = {title: null, message: null};
      info.message = libBookStatus === BOOK_OPEN_STATUS ? '图书状态开放' : '图书状态关闭';
      changeBookStatus(param).then(res => {
        info.title = res.data > 0 ? SUCCESS_MSG : ERROR_MSG;
        if (res.data > 0) this.$notify.success(info);
        else this.$notify.error(info);
        this.getList();
      })
    },

    // 展示当前图书的介绍弹框
    showBookIntroductionCard(row) {
      this.bookIntroductionDialog.cover = row.libBookCover;
      this.bookIntroductionDialog.title = row.libBookName;
      this.bookIntroductionDialog.introduction = row.libBookIntroduction
      this.bookIntroductionDialog.open = true;
    },

    /** 查询图书馆-图书列表 */
    getList() {
      this.loading = true;
      pageBook(this.queryParams).then(response => {
        this.bookList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        libBookId: null,
        libBookName: null,
        libBookCover: null,
        libBookIntroduction: null,
        libBookType: null,
        libBookAuthor: null,
        libBookPublishHouse: null,
        libBookPublishTime: null,
        libBookStatus: null,
        libBookStock: null,
        libBookPrice: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.libBookId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加图书";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const libBookId = row.libBookId || this.ids
      getBook(libBookId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改图书";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.libBookId != null) {
            updateBook(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            this.form.libBookStatus = BOOK_OPEN_STATUS;
            addBook(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const libBookIds = row.libBookId || this.ids;
      this.$modal.confirm('是否确认删除图书馆-图书编号为"' + libBookIds + '"的数据项？').then(function () {
        return delBook(libBookIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('library/book/export', {
        ...this.queryParams
      }, `book_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>

<style>
/* 自定义对话框样式 */
.scroll-dialog .el-dialog__body {
  max-height: 70vh;
  overflow-y: auto;
}

.demo-table-expand {
  font-size: 0;
}

.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}

.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 50%;
}
</style>
